package com.ruanruan.hadoop.mr;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.net.URI;
import java.util.*;


public class WordCount {

    /**
     * 拆分单词的Mapper
     */
    public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private Set<String> skipWordSet = new HashSet<>();

        /**
         * 载入停词表
         *
         * @param context 上下文
         * @throws IOException
         */
        @Override
        protected void setup(Context context) throws IOException {
            Configuration conf = context.getConfiguration();

            //如果没有-skip参数则跳过停词表的载入
            if (!conf.getBoolean("wordcount.skip.patterns", false)) {
                return;
            }
            //载入停词表
            URI[] cacheFiles = Job.getInstance(conf).getCacheFiles();
            for (URI cacheFile : cacheFiles) {
                Path path = new Path(cacheFile);
                parseCacheFile(path.getName());
            }

        }

        /**
         * 解析缓存文件
         *
         * @param fileName 文件名
         */
        private void parseCacheFile(String fileName) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
                bufferedReader.lines().forEach(f -> skipWordSet.add(f.replaceAll(" ","")));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            //替换掉特殊符号，并转换为小写
            String regEx = "[\t\n`~!@#$%^&*()+=|{}':;'\\-,\\[\\].<>/?~0-9]";
            String temp = value.toString().replaceAll(regEx, " ").toLowerCase();

            //切割出所有单词
            StringTokenizer tokenizer = new StringTokenizer(temp);
            while (tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                if (!skipWordSet.contains(token)) {
                    //如果不在停词表内则将Key、Value写入Context
                    word.set(token);
                    context.write(word, one);
                }

            }

        }
    }

    /**
     * 对单词分组统计的Reducer
     */
    public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        private IntWritable result = new IntWritable();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            //计算values的个数
            for (IntWritable value : values) {
                sum += value.get();
            }
            //输出到Context
            result.set(sum);
            context.write(key, result);
        }
    }


    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        //创建Configuration
        Configuration conf = new Configuration();
        //配置hadoop远程登陆,打成jar包执行的时候不需要设置
        System.setProperty("HADOOP_USER_NAME","hadoop");
        conf.set("fs.defaultFS","hdfs://192.168.1.112:8020");

        //获取命令行输入的参数
        GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
        String[] remainingArgs = optionParser.getRemainingArgs();

        //参数校验
        if (!(remainingArgs.length != 2 || remainingArgs.length != 4)) {
            System.err.println("Usage: wordcount <in> <out> [-skip skipPatternFile]");
            System.exit(2);
        }

        //创建作业
        Job job = Job.getInstance(conf, "word count");

        //设置Jar
        job.setJarByClass(WordCount.class);

        //设置Mapper
        job.setMapperClass(TokenizerMapper.class);
        //设置Mapper输入和输出
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        //设置Reducer
        job.setReducerClass(IntSumReducer.class);

        //设置作业的输入和输出
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        //获取停词表
        List<String> otherArgs = new ArrayList<>();
        for (int i = 0; i < remainingArgs.length; ++i) {
            //如果有-skip参数，则将停词表加入缓存中
            if ("-skip".equals(remainingArgs[i])) {
                job.addCacheFile(new Path(remainingArgs[++i]).toUri());
                job.getConfiguration().setBoolean("wordcount.skip.patterns", true);
            } else {
                otherArgs.add(remainingArgs[i]);
            }
        }

        //设置作业的输入和输出路径
        FileInputFormat.addInputPath(job, new Path(otherArgs.get(0)));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs.get(1)));

        //等待作业完成
        boolean flag = job.waitForCompletion(true);
        System.out.println("Succeed! " + flag);
        System.exit(flag ? 0 : 1);

    }

}
